package com.xishu.controller;

import com.xishu.annotation.valid.Admin;
import com.xishu.annotation.valid.MethodValidator;
import com.xishu.config.Config;
import com.xishu.entity.foodpanda.Menu;
import com.xishu.entity.shop.SceneTimeConfig;
import com.xishu.entity.shop.Shop;
import com.xishu.foodpanda.FoodPandaClient;
import com.xishu.foodpanda.FoodPandaConfigService;
import com.xishu.foodpanda.FoodPandaImportService;
import com.xishu.response.ResponseData;
import com.xishu.response.ResponseStatus;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.SceneService;
import com.xishu.service.ShopService;
import com.xishu.service.ZhEnService;
import com.xishu.util.DateUtil;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "foodpanda Menu配置")
@RestController
public class MenuController implements Tools {
    private CommonService commonService = CommonService.getInstance();
    private Config config = Config.getInstance();
    private FoodPandaConfigService foodPandaConfigService = FoodPandaConfigService.getInstance();

    @ApiOperation(value = "查询")
    @PutMapping(value = ("/menu"), produces = ("application/json;charset=UTF-8"))
    public ResponseData query(@RequestBody Menu menu) throws Exception {
        return commonService.searchResponse(menu);
    }

    @ApiOperation(value = "修改")
    @PutMapping(value = ("/menu/modify"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    public ResponseData modify(@RequestBody Menu menu) throws Exception {
        VerifyUtil.verify(() -> menu.getId() != null);
        VerifyUtil.verify(() -> menu.getTimeConfigList() != null);

        Menu menuInDb = foodPandaConfigService.findMenuById(menu.getId());

        int menuType = 0;
        if (menu.getMenuType() != null) {
            menuType = menu.getMenuType();
        } else {
            menuType = menuInDb.getMenuType();
        }

        List<Menu> menuList = foodPandaConfigService.findMenuList(menuInDb.getShopId(), menuType);

        //过滤其它场景
        List<Menu> otherMenuList = menuList.stream().filter(p -> !equals(p.getId(), menu.getId())).collect(Collectors.toList());
        List<SceneTimeConfig> sceneTimeConfigList = otherMenuList.stream().flatMap(p -> getList(p.getTimeConfigList()).stream()).collect(Collectors.toList());

        for (SceneTimeConfig sceneTimeConfig : menu.getTimeConfigList()) {
            SceneService.getInstance().isTimeConfigValid(sceneTimeConfig);
            VerifyUtil.verify(() -> !SceneService.getInstance().isTimeConfigCheckWithInteger(sceneTimeConfig, sceneTimeConfigList), ResponseStatus.SCENE_TIME_CONFLICT);
        }

        return commonService.modifyObject(menu);
    }

    @ApiOperation(value = "创建")
    @PostMapping(value = ("/menu"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true, checkShopId = true)
    public ResponseData create(@RequestBody Menu menu) throws Exception {
        VerifyUtil.verify(() -> isNotEmpty(isNotEmpty(menu.getShopId())));
        VerifyUtil.verify(() -> isNotEmpty(menu.getTimeConfigList()));
        VerifyUtil.verify(() -> isNotEmpty(menu.getName()));
        VerifyUtil.verify(() -> menu.getMenuType() != null);

        List<Menu> menuList = foodPandaConfigService.findMenuList(menu.getShopId(), menu.getMenuType());
        List<SceneTimeConfig> sceneTimeConfigList = menuList.stream().flatMap(p -> getList(p.getTimeConfigList()).stream()).collect(Collectors.toList());

        for (SceneTimeConfig sceneTimeConfig : menu.getTimeConfigList()) {
            SceneService.getInstance().isTimeConfigValid(sceneTimeConfig);
            VerifyUtil.verify(() -> !SceneService.getInstance().isTimeConfigCheckWithInteger(sceneTimeConfig, sceneTimeConfigList), ResponseStatus.MENU_TIME_CONFLICT);
        }

        //处理国际化
        ZhEnService.getInstance().dealZhEn(menu);

        return commonService.createObject(menu);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping(value = ("/menu"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    public ResponseData delete(@RequestBody Menu menu) throws Exception {
        return commonService.delete(menu);
    }

    @ApiOperation(value = "导入分店下面所有的菜单")
    @PostMapping(value = ("/menu/import/to/foodpanda"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true, checkShopId = true)
    public ResponseData importAllMenu(@RequestBody Menu menu) throws Exception {
        Long shopId = menu.getShopId();
        VerifyUtil.verify(() -> shopId != null);
        Shop shop = ShopService.getInstance().findShopById(shopId);
        FoodPandaImportService.getInstance().importCatalogList(shop);
        return ResponseData.emptyResponse();
    }

    @ApiOperation(value = "查询导入日志")
    @PostMapping(value = ("/menu/import/log"), produces = ("application/json;charset=UTF-8"))
    @Admin
    public ResponseData getImportLog(@RequestBody Shop shop) throws Exception {
        Long shopId = shop.getId();
        shop = ShopService.getInstance().findShopById(shopId);
        String uri = String.format("/v2/chains/%s/vendors/%s/menu-import-logs", shop.getFoodPandaConfig().getChainCode(), shop.getFoodPandaConfig().getVendors());

        //当天的时间
        Map map = new HashMap<String, String>();
        //2016-01-02T00:00:00Z
        //yyyy-MM-dd HH:mm:ss
        map.put("from", String.format("%sT%sZ", DateUtil.format(System.currentTimeMillis() - DateUtil.ONE_DAY, "yyyy-MM-dd"), DateUtil.format(System.currentTimeMillis() - DateUtil.ONE_DAY, "HH:mm:ss")));
        String token = FoodPandaImportService.getInstance().login(shop);

        String log = FoodPandaClient.getInstance().getLog(uri, map, token);
        return commonService.createResponse(log);
    }

}

